package com.osi.mes.qm.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;

/**
 * 文件选择器
 */
public class MyFileChooser extends JFileChooser {

	private static final long serialVersionUID = 1L;

	private static MyFileChooser instance = null;

	private MyFileChooser() {
		super();
		setAcceptAllFileFilterUsed(false);
		setMultiSelectionEnabled(false);
	}

	public static MyFileChooser getInstance() {
		if (instance == null) {
			instance = new MyFileChooser();
		}
		return instance;
	}

	public void setInfo(String[][] fileFiter, String title, boolean isView) {
		resetChoosableFileFilters();
		if (fileFiter != null) {
			FileFiters ffs = new FileFiters(fileFiter);
			this.setFileFilter(ffs);
		} else {
			this.setFileFilter(null);
		}
		setDialogTitle(title);
		if (isView) {
			ImagePreviewPanel ipp = new ImagePreviewPanel();
			setAccessory(ipp);
			addPropertyChangeListener(ipp);
		} else {
			setAccessory(null);
			addPropertyChangeListener(null);
		}
	}

	public File showOpenFileChooser() {
		this.setMultiSelectionEnabled(false);
		int ret = showOpenDialog(null);
		if (ret == JFileChooser.CANCEL_OPTION) {
			return null;
		}
		return getSelectedFile();
	}

	public File[] showOpenFiles() {
		this.setMultiSelectionEnabled(true);
		int ret = showOpenDialog(null);
		if (ret == JFileChooser.CANCEL_OPTION) {
			return new File[0];
		}
		return getSelectedFiles();
	}

	public File showSaveFileChooser(String saveName) {
		this.setSelectedFile(new File(saveName));
		this.setDialogType(SAVE_DIALOG);
		int ret = this.showSaveDialog(null);
		if (ret == JFileChooser.CANCEL_OPTION) {
			return null;
		}

		File file = getSelectedFile();
		if (file == null) 
			return null;

		file.setExecutable(true, false);
		file.setReadable(true, false);
		file.setWritable(true, false);
		
		if (file.exists()) {

			int i = JOptionPane.showConfirmDialog(this, "是否要替换原文件？", "文件重名！",
					JOptionPane.YES_NO_OPTION);

			if (i != 0) {
				return showSaveFileChooser(saveName);
			}

			file.delete();
		}

		return file;
	}

	class FileFiters extends FileFilter {
		private String fileList[][] = null;

		public FileFiters(String _fileList[][]) {
			fileList = _fileList;
		}

		public boolean accept(File file) {
			if (isTrue(file.getName().toUpperCase()) || file.isDirectory()) {
				return true;
			}

			return false;
		}

		public String getDescription() {
			String str = "";
			for (int i = 0; i < fileList.length; i++) {
				str += fileList[i][1] + " ; ";
			}

			return str.substring(0, str.lastIndexOf(";"));
		}

		private boolean isTrue(String filename) {
			filename = filename.toUpperCase();
			for (int i = 0; i < fileList.length; i++) {
				if (filename.endsWith(fileList[i][0].toUpperCase())) {
					return true;
				}
			}

			return false;
		}
	}

	class ImagePreviewPanel extends JPanel implements PropertyChangeListener {

		private static final long serialVersionUID = -2435224881926548613L;

		private static final int ACCSIZE = 120;

		private JLabel iconLabel = new JLabel();

		public ImagePreviewPanel() {
			setPreferredSize(new Dimension(ACCSIZE, -1));
			iconLabel.setPreferredSize(new Dimension(80, 80));
			this.add(iconLabel, BorderLayout.CENTER);
		}

		/**
		 * bound 属性发生更改时调用此方法，即当用户选中图像时，调用此方法。
		 */
		public void propertyChange(PropertyChangeEvent e) {
			String propertyName = e.getPropertyName();

			if (propertyName
					.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
				File selection = (File) e.getNewValue();
				String name;

				if (selection == null)
					return;
				else
					name = selection.getAbsolutePath();

				if ((name != null) && name.toLowerCase().endsWith(".jpg")
						|| name.toLowerCase().endsWith(".jpeg")
						|| name.toLowerCase().endsWith(".gif")
						|| name.toLowerCase().endsWith(".png")) {
					ImageIcon icon = scaleImage(new ImageIcon(name));
					iconLabel.setIcon(icon);
					repaint();
				}
			}
		}

		/**
		 * 剪裁图像
		 */
		private ImageIcon scaleImage(ImageIcon icon) {
			int width = icon.getIconWidth();
			int height = icon.getIconHeight();

			if (width <= 80 && height <= 80) {
				return icon;
			}
			Image image = icon.getImage();
			image = image.getScaledInstance(80, 80, Image.SCALE_DEFAULT);

			return new ImageIcon(image);
		}
	}

}
